package demo1;

/**
 * @author xianyu
 * @version 1.0
 * @date 2020/5/11 21:55
 * 两个线程交替打印1-100
 */
public class NumberPrintTest {
    public static void main(String[] args) {
        Number1 number1 = new Number1();
        Thread t1 = new Thread(number1);
        Thread t2 = new Thread(number1);

        t1.setName("线程1");
        t2.setName("线程2");

        t1.start();
        t2.start();
    }
}

class Number1 implements Runnable{
    private int num = 1;
    private Object obj = new Object();
    @Override
    public void run() {
        while(true){
            synchronized (obj){
                obj.notify();
                if(num<=100){
                    System.out.println(Thread.currentThread().getName() + ": " + num);
                    num++;
                    try {
                        //使得调用如下wait()方法的线程进入阻塞状态
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }else{
                    break;
                }
            }
        }
    }
}